package com.cm.projectx.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cm.projectx.common.PageInfo;
import com.cm.projectx.common.entity.UserContext;
import com.cm.projectx.entity.ProductInfo;
import com.cm.projectx.entity.TaskTemplate;
import com.cm.projectx.mapper.TaskTemplateMapper;
import com.cm.projectx.response.Result;
import com.cm.projectx.service.IPriceTaskService;
import com.cm.projectx.service.IProductInfoService;
import com.cm.projectx.service.IProductService;
import com.cm.projectx.service.ITaskTemplateService;
import com.cm.projectx.util.SimplePage;
import com.cm.projectx.vo.ProductMonitorRelation;
import com.cm.projectx.vo.QueryTaskTemplateVO;
import com.cm.projectx.vo.TaskTemplateVo;
import com.cm.projectx.vo.TaskVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TaskTemplateServiceImpl extends ServiceImpl<TaskTemplateMapper, TaskTemplate> implements ITaskTemplateService {

    @Autowired
    private IPriceTaskService priceTaskService;

    @Autowired
    private TaskTemplateMapper taskTemplateMapper;

    @Autowired
    private IProductInfoService productInfoService;

    @Override
    public boolean saveTemplate(TaskVo taskVo, String templateName) {
        String dataScope = UserContext.getUserDataScope();
        // 检查模板名称是否重复
        long count = this.count(Wrappers.<TaskTemplate>lambdaQuery()
                .eq(TaskTemplate::getTemplateName, templateName)
                .eq(TaskTemplate::getStatus, "0"));
        if (count > 0) {
            throw new RuntimeException("模板名称已存在");
        }
        TaskTemplate template = new TaskTemplate();
        template.setTemplateCode(UUID.randomUUID().toString().replaceAll("-", ""));
        template.setTemplateName(templateName);
        template.setTaskName(taskVo.getTaskName());
        template.setTemplateContent(JSON.toJSONString(taskVo));
        template.setStatus("0");
        template.setCreateTime(new Date());
        template.setUpdateTime(new Date());
        //todo权限
        template.setArea(dataScope);
        return this.save(template);
    }

    @Override
    public boolean deleteTemplate(String templateCode) {
        TaskTemplate template = this.getOne(Wrappers.<TaskTemplate>lambdaQuery()
                .eq(TaskTemplate::getTemplateCode, templateCode)
                .eq(TaskTemplate::getStatus, "0"));
        if (template == null) {
            throw new RuntimeException("模板不存在");
        }
        template.setStatus("1");
        template.setUpdateTime(new Date());
        return this.updateById(template);
    }

    @Override
    public Result  updateTemplate(TaskTemplateVo templateVo) {
        try {
            String templateCode = templateVo.getTemplateCode();
            String operationType = templateVo.getOperationType();

            if (StringUtils.isBlank(templateCode)) {
                return new Result(-1, "模板编码不能为空", null);
            }

            // 获取原模板信息
            TaskTemplate template = this.getOne(Wrappers.<TaskTemplate>lambdaQuery()
                    .eq(TaskTemplate::getTemplateCode, templateCode)
                    .eq(TaskTemplate::getStatus, "0"));

            if (template == null) {
                return new Result(-1, "模板不存在", null);
            }

            // 检查模板名称是否重复（排除自身）
            if (!template.getTemplateName().equals(templateVo.getTemplateName())) {
                long count = this.count(Wrappers.<TaskTemplate>lambdaQuery()
                        .eq(TaskTemplate::getTemplateName, templateVo.getTemplateName())
                        .eq(TaskTemplate::getStatus, "0")
                        .ne(TaskTemplate::getTemplateCode, templateCode));
                if (count > 0) {
                    return new Result(-1, "模板名称已存在", null);
                }
            }

            // 更新模板信息
            template.setTemplateName(templateVo.getTemplateName());
            template.setTaskName(templateVo.getTaskName());

            // 更新任务数据
            if (templateVo.getTaskVo() != null) {
                templateVo.getTaskVo().setTaskName(templateVo.getTaskName());
                template.setTemplateContent(JSON.toJSONString(templateVo.getTaskVo()));
            }

            template.setUpdateTime(new Date());
            boolean updateResult = this.updateById(template);

            if (!updateResult) {
                return new Result(-1, "更新模板失败", null);
            }

            HashMap<String, Object> data = new HashMap<>();
            data.put("templateCode", template.getTemplateCode());
            data.put("templateName", template.getTemplateName());

            // 如果操作类型是dispatch，则进行任务下发
            if ("1".equals(operationType)) {
                Result dispatchResult = createTaskFromTemplate(template.getTemplateContent(), templateVo.getTaskName());
                if (dispatchResult.getCode() == 0) {
                    data.put("taskDispatch", true);
                    data.put("taskInfo", dispatchResult.getData());
                    return new Result(0, "模板更新并任务下发成功", data);
                } else {
                    // 下发失败，但模板已更新，返回部分成功结果
                    data.put("taskDispatch", false);
                    data.put("taskError", dispatchResult.getMsg());
                    return new Result(0, "模板更新成功，但任务下发失败", data);
                }
            }
            return new Result(0, "模板更新成功", data);

        } catch (Exception e) {
            log.error("更新模板异常", e);
            return new Result(-1, "更新模板失败: " + e.getMessage(), null);
        }
    }

    @Override
    public Result createTaskFromTemplate(String templateContent,String taskName) {
        try {
            // 解析模板内容
            TaskVo taskVo = JSON.parseObject(templateContent, TaskVo.class);
            if (taskVo == null) {
                return new Result(-1, "模板内容解析失败", null);
            }
            // 调用任务服务创建任务
            return priceTaskService.createAndDispatchTask(taskVo);

        } catch (Exception e) {
            log.error("根据模板创建任务异常", e);
            return new Result(-1, "任务创建失败: " + e.getMessage(), null);
        }
    }

    @Override
    public PageInfo<TaskTemplate> getTemplateList(QueryTaskTemplateVO queryTaskTemplateVO) {
        LambdaQueryWrapper<TaskTemplate> taskLambdaQueryWrapper = buildTaskQueryWrapper(queryTaskTemplateVO, true);
        //构建分页
        IPage<TaskTemplate> page = new SimplePage<>(queryTaskTemplateVO);
        page = taskTemplateMapper.selectPage(page,taskLambdaQueryWrapper);
        return SimplePage.toPageResult(page, TaskTemplate.class);
    }

    @Override
    public Result getTemplateDetail(String templateCode) {
        Result result = new Result();
        try {
            TaskTemplate template = this.getOne(new LambdaQueryWrapper<TaskTemplate>()
                    .eq(TaskTemplate::getTemplateCode, templateCode)
                    .eq(TaskTemplate::getStatus, "0"));

            if (template == null) {
                return new Result(-1, "模板不存在", null);
            }
            // 解析模板内容
            TaskVo taskVo = JSON.parseObject(template.getTemplateContent(), TaskVo.class);

            TaskTemplateVo templateVo = new TaskTemplateVo();
            templateVo.setId(template.getId());
            templateVo.setTemplateCode(template.getTemplateCode());
            templateVo.setTemplateName(template.getTemplateName());
            templateVo.setTaskName(template.getTaskName());
            templateVo.setTaskVo(taskVo);
            List<Map<String, Object>> productList = new ArrayList<>();
            //商品监测点列表
            String productInfo = JSON.toJSONString(taskVo.getProductMonitorRelations());
            if(StrUtil.isNotEmpty(productInfo)){
                JSONArray productArray = JSONUtil.parseArray(productInfo);
                for (Object o : productArray) {
                    Map<String, Object> productMap = new HashMap<>();
                    JSONObject product = (JSONObject) o;
                    ProductInfo productDetail = productInfoService.getById(StrUtil.toString(product.get("productId")));
                    if (productDetail == null) {
                        continue;
                    }
                    productMap.put("id", productDetail.getId());
                    productMap.put("name", productDetail.getName());
                    productMap.put("kind", productDetail.getKind());
                    productMap.put("unit", productDetail.getUnit());
                    productMap.put("floatingValue", ((BigDecimal)product.get("floatingValue")).floatValue());
                    JSONArray monitors = (JSONArray) product.get("monitors");
                    if(CollUtil.isNotEmpty(monitors)){
                        List<Object> monitorNames = monitors.stream().map(o1 -> ((JSONObject) o1).get("monitorName")).collect(Collectors.toList());
                        productMap.put("monitorPoints", StrUtil.join(StrPool.COMMA, monitorNames));
                    }
                    productList.add(productMap);
                }
            }
            result.addData("productList", productList);
            result.addData("templateDetail", templateVo);
           return result;
        } catch (Exception e) {
            log.error("获取模板详情异常", e);
            return new Result(-1, "获取模板详情失败", null);
        }
    }



    private LambdaQueryWrapper<TaskTemplate> buildTaskQueryWrapper(QueryTaskTemplateVO taskTemplateVO, boolean addDataScope) {
        LambdaQueryWrapper<TaskTemplate> queryWrapper = Wrappers.lambdaQuery();
        // 添加数据权限条件（可选）
        if (addDataScope) {
            String dataScope = UserContext.getUserDataScope();
            if (!"市人员".equals(dataScope) && StringUtils.isNotBlank(dataScope)) {
                queryWrapper.like(TaskTemplate::getArea, dataScope);
            }
        }
        // 添加任务名称条件
        if (StringUtils.isNotBlank(taskTemplateVO.getTaskName())) {
            queryWrapper.like(TaskTemplate::getTaskName, taskTemplateVO.getTaskName());
        }
        // 模板
        if (StringUtils.isNotBlank(taskTemplateVO.getTemplateName())) {
            queryWrapper.like(TaskTemplate::getTemplateName, taskTemplateVO.getTemplateName());
        }
        // 添加时间区间条件（根据createTime查询）
        if (taskTemplateVO.getStartTime() != null && taskTemplateVO.getEndTime() != null) {
            // 开始时间和结束时间都不为空，查询区间
            queryWrapper.between(TaskTemplate::getCreateTime, taskTemplateVO.getStartTime(), taskTemplateVO.getEndTime());
        } else if (taskTemplateVO.getStartTime() != null) {
            // 只有开始时间，查询大于等于开始时间
            queryWrapper.ge(TaskTemplate::getCreateTime, taskTemplateVO.getStartTime());
        } else if (taskTemplateVO.getEndTime() != null) {
            // 只有结束时间，查询小于等于结束时间
            queryWrapper.le(TaskTemplate::getCreateTime, taskTemplateVO.getEndTime());
        }
        //排除模板类型的数据
        queryWrapper.eq(TaskTemplate::getStatus,"0");
        queryWrapper.orderByDesc(TaskTemplate::getUpdateTime);
        return queryWrapper;
    }

}
